#!/usr/bin/env python

import sys,os
import getopt
import time



def usage():
    print "usage:"
    print sys.argv[0]," -f file -p output_path"
    #print "In default outfile like asn.yymmdd iplist.yymmdd"
    sys.exit()


def main():
    t=time.gmtime()
    date=time.strftime(".%y%m%d",t)
    mask=dict()
    mask["1"]='32'
    mask["2"]='31'
    mask['4']='30'
    mask['8']='29'
    mask['16']='28'
    mask['32']='27'
    mask['64']='26'
    mask['128']='25'
    mask['256']='24'
    mask['512']='23'
    mask['1024']='22'
    mask['2048']='21'
    mask['4096']='20'
    mask['8192']='19'
    mask['16384']='18'
    mask["32768"]='17'
    mask["65536"]='16'
    mask["131072"]='15'
    mask["262144"]='14'
    mask["524288"]='13'
    mask["1048576"]='12'
    mask["2097152"]='11'
    mask["4194304"]='10'
    mask["8388608"]='9'
    mask["16777216"]='8'
    mask["33554432"]='7'
    mask["67108864"]='6'
    mask["134217728"]='5'
    mask["268435456"]='4'
    mask["536870912"]='3'
    mask["1073741824"]='2'
    mask["2147483648"]='1'
    try:
        opts, arg = getopt.getopt(sys.argv[1:],"f:p:")
#except:
    except getopt.error, msg:
        print msg
        usage()
    fpath=""
    path=""
    for i in opts:
        if i[0] == "-f":
            fpath=i[1]
            w=os.path.isfile(fpath)
            if not w:
                print "ERROR! %s is not existing!"%fpath
                usage()
        elif i[0] == "-p":
            path=i[1]
            w=os.path.isdir
            if not w:
                print "ERROR! PATH %s not existing!"
        else:
            pass
    if fpath=="" or path=="" :
        print "ERROR! need more argv!"
        usage()
    asnfile=path+"cn_asn_list"+date
    ipfile=path+"cn_ip_list"+date
    asn=open(asnfile,"w")
    ipl=open(ipfile,"w")
    for i in open(fpath):
        i=i.strip("\r\n")
        if i[0]=="#" or i[0]=="":
            continue;
        p=i.split("|")
        if p[1] =="CN":
            if p[2]=="asn":
                asn.write(p[3]+"\n")
            elif p[2]=="ipv4":
                ipl.write(p[3]+"/"+mask[p[4]]+"\n")
            elif p[2]=="ipv6":
                pass
            else:
                continue
    asn.close()      
    ipl.close()
    os.popen("ln -sf %s %s")%(asnfile,path+"cn_asn_list")
    os.popen("ln -sf %s %s")%(ipfile,path+"cn_ip_list")
main()   